#!/usr/bin/env python

"""
Create input for the mirrorlist servers.
"""

import sys
import re
import os
import argparse


sys.path.insert(0, os.path.join(os.path.dirname(
    os.path.abspath(__file__)), '..'))
import mirrormanager2.lib.mirrorlist


def main():
    default_pkl = '/var/lib/mirrormanager/mirrorlist_cache.pkl'
    default_proto = '/var/lib/mirrormanager/mirrorlist_cache.proto'
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument(
        "-c", "--config",
        dest="config",
        default='/etc/mirrormanager/mirrormanager2.cfg',
        help="Configuration file to use "
        "(default=/etc/mirrormanager/mirrormanager2.cfg)")
    parser.add_argument(
        "-o", "--output",
        const=default_pkl,
        dest="output", nargs='?',
        help="pkl output file")
    parser.add_argument(
        "-p", "--protobuf",
        const=default_proto,
        dest="proto", nargs='?',
        help="proto output file")

    args = parser.parse_args()

    d = dict()
    with open(args.config) as config_file:
        exec(compile(config_file.read(), args.config, 'exec'), d)

    session = mirrormanager2.lib.create_session(d['DB_URL'])

    if args.output is None:
        output = default_pkl
    else:
        output = args.output

    mirrormanager2.lib.mirrorlist.populate_all_caches(session)
    if output != "None":
        mirrormanager2.lib.mirrorlist.dump_caches(session, filename=output)
    if args.proto is not None:
        mirrormanager2.lib.mirrorlist.dump_caches(
            session,
            protobuf_file=args.proto
        )

    return 0


if __name__ == "__main__":
    sys.exit(main())
